package com.rover.system.service;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.grid.DataGrid;
import com.rover.system.entity.FormTableField;
import com.rover.system.entity.FormTableInfo;
import com.utils.DateUtil;
import com.utils.FileUtil;
import com.utils.ResourceUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.grid.Page;
import com.rover.system.dao.BaseDao;

@Service
@Transactional
public class FormTableInfoService  extends BaseService {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private BaseDao dao;
    @Autowired
    private  FormTableFieldService   formTableFieldService;
    @Autowired
    private    CodeService   codeService;
	@Transactional
	public DataGrid query(Page page) throws Exception {
        DataGrid dataGrid=new DataGrid();
		List<FormTableInfo> li=dao.findPageHql(page.getHQL(), page.getWhereParams(), page.getPageNo(),
				page.getPageSize());
        dataGrid.setResult(li);
        dataGrid.setTotalCount(dao.countHql(page.getHQLTotalCount(), page.getWhereParams()));
		return dataGrid;
		// return
		// userDao.find("select new Tuser(t.id,t.name,t.createdatetime,t.modifydatetime) from Tuser t ");
	}

	/*
	 * 添加的时候判断名称是否重复
	 * @name 要判断的名称
	 * */
	public Boolean isPhysicalNameRepeat(FormTableInfo formTableInfo){
		String hql="select count(tableID) from FormTableInfo where physicalName=:physicalName";
		 Map<String, Object> params=new HashMap<String, Object>();
		 params.put("physicalName", formTableInfo.getPhysicalName());
        if(formTableInfo.getTableId()!=null){
            hql+=" and tableId!=:tableId";
            params.put("tableId", formTableInfo.getTableId());
        }
		if(dao.countHql(hql, params)>0){
			return true;
		}
		else
			return false;
	}


    public  void generatePage(Integer tableId,String getRealPath) throws IOException {
        FormTableInfo formTableInfo=getEntity(FormTableInfo.class, tableId);
        //得到要生成 Controller、entity\service的生成路径
        String generatePath=getRealPath.substring(0,getRealPath.lastIndexOf('\\')+1)+ ResourceUtil.getGeneratePath();
        //包的前路径         例：crm.rover
          String   strPackage=(generatePath.substring(generatePath.indexOf("crm"),generatePath.length())).replace("\\",".");
        //实体
        generateEntity(formTableInfo,generatePath,strPackage);
             //service
        generateService(formTableInfo,generatePath,strPackage);
       //controller
        generateController(formTableInfo,generatePath,strPackage);

        //page
        if(formTableInfo.getIsJS().equals(1))
        generateJS(formTableInfo,getRealPath,generatePath,strPackage);
        else
            generatePage(formTableInfo,getRealPath,generatePath,strPackage);
        System.out.println("strPackage:"+strPackage);
        System.out.println(generatePath);
        System.out.println(new File(generatePath).exists());
        System.out.println(getRealPath);
    }

    //首字母小写
    private  String firstLower(String param){
        return  param.substring(0,1).toLowerCase()+param.substring(1);
    }
    //首字母大写
    private  String firstUpper(String param){
        return   param.substring(0,1).toUpperCase()+param.substring(1);
    }
    /*
    *     Velocity的配置信息
    *      @param path       主要用于得到模版路径
     *      */
    private  VelocityEngine getVelocityEngine(String path){
        VelocityEngine ve = new VelocityEngine();
        //模板文件所在的路径
        //设置参数
        ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, ( path.substring(0,path.indexOf("java\\"))+"resources\\formTemplate"));
        //处理中文问题
        ve.setProperty(Velocity.INPUT_ENCODING,"UTF-8");
        ve.setProperty(Velocity.OUTPUT_ENCODING,"UTF-8");
        return  ve;
    }

    /*
    *       生成实体类
    *  @param   formTableInfo        实体类信息
      *  @param  strGeneratePath        生成路径
        *  @param    strPackage  包的前缀路径   例：crm.rover
       *  */
    private void generateEntity(FormTableInfo formTableInfo,String strGeneratePath,String strPackage) throws IOException {
        //创建实体类系的文件夹
        String entityPath=strGeneratePath+"\\entity\\"+firstLower(formTableInfo.getEntityPackage());
        FileUtil.makeDir(entityPath);

        //获取模板引擎
        VelocityEngine ve=getVelocityEngine(entityPath);
        try
        {
            //初始化模板
            ve.init();
            //获取模板(hello.html)
            //Velocity模板的名称
            Template template = ve.getTemplate("entity.vm");
            //获取上下文
            VelocityContext context = new VelocityContext();
            //把数据填入上下文
            context.put("package", strPackage+".entity."+firstLower(formTableInfo.getEntityPackage().replace("\\",".").replace("/",".")));
            context.put("tableName",formTableInfo.getTableName());
            context.put("physicalName",formTableInfo.getPhysicalName());
            context.put("entityName",firstUpper(formTableInfo.getEntityName()));
            List<FormTableField>         listField= formTableFieldService.getTableField(formTableInfo.getTableId());
            StringBuilder sb=new StringBuilder();
            sb.append("@ViewField\n");
            sb.append("private Integer id;\n");
            sb.append("@Id\n");
            if(formTableInfo.getGenerationType().toLowerCase().equals("identity")){
                sb.append("@GeneratedValue(strategy=GenerationType.IDENTITY)\n");
            }
            else{
                sb.append("@GeneratedValue(strategy = GenerationType.SEQUENCE,generator =\"generator\")\n");
                String strSeq= "seq_"+formTableInfo.getEntityName();
                if(formTableInfo.getOracleSequence()!=null) {
                    strSeq=formTableInfo.getOracleSequence();
                }
                 sb.append("@SequenceGenerator(name = \"generator\",allocationSize = 1, sequenceName=\""+strSeq+"\")\n");
            }
            sb.append(" public Integer getId() {return id;}\n");
            sb.append(" public void setId(Integer id) {\n" +
                    "        this.id = id;\n" +
                    "    }\n");

            for(FormTableField field:listField){
                //unique 可选,是否在该列上设置唯一约束(默认值false)
                boolean unique=field.getIsForeignKey().equals(1);
                //nullable 可选,这个字段在保存时必需有值(默认值true)
                boolean nullable=!field.getMustFill().equals(1);
              boolean dispInGrid=  !field.getDispInGrid().equals(1);
                switch(field.getControlType()){
                    case"datefield":
                        sb.append("@ViewField(header = \""+field.getFieldDisplayName()+"\", width=150,hidden="+dispInGrid+", align = \"center\",type = \"date\",attributes=\"yyyy-MM-dd hh:mm:ss\")\n");
                        break;
                    case"numberfield":
                    case"textarea":
                    case"textfield":
                        if(StringUtils.isBlank( field.getCodeName()))
                            sb.append("@ViewField(header = \""+field.getFieldDisplayName()+"\", width = 80,hidden="+dispInGrid+")\n");
                        else
                            sb.append("@ViewField(header = \""+field.getFieldDisplayName()+"\", width = 80,hidden="+dispInGrid+", align = \"center\",type=\"code\" ,attributes=\""+field.getCodeName()+"\")\n");
                        break;
                    default:
                        sb.append("@ViewField(hidden="+dispInGrid+")\n");
                        break;
                }

                switch(field.getFieldType().toLowerCase()) {
                    case "date":
                        sb.append("private Date "+firstLower(field.getFieldName())+";\n");
                        sb.append("@Column(unique="+unique+" ,nullable="+nullable+" )\n");
                        sb.append("public Date get"+firstUpper(field.getFieldName())+"() {\n" +
                                "\t\treturn "+firstLower(field.getFieldName())+";\n" +
                                "}\n");
                        sb.append("public void set"+firstUpper(field.getFieldName())+"(Date "+firstLower(field.getFieldName())+") {\n" +
                                "\t\tthis."+firstLower(field.getFieldName())+" = "+firstLower(field.getFieldName())+";\n" +
                                "}\n");
                        break;
                    case "decimal":
                        sb.append("private BigDecimal "+firstLower(field.getFieldName())+";\n");
                        sb.append("@Column(scale="+field.getDecimalPlaces()+" ,unique ="+unique+" ,nullable="+nullable+" )\n");
                        sb.append("public BigDecimal get"+firstUpper(field.getFieldName())+"() {\n" +
                                "\t\treturn "+firstLower(field.getFieldName())+";\n" +
                                "}\n");
                        sb.append("public void set"+firstUpper(field.getFieldName())+"(BigDecimal "+firstLower(field.getFieldName())+") {\n" +
                                "\t\tthis."+firstLower(field.getFieldName())+" = "+firstLower(field.getFieldName())+";\n" +
                                "}\n");
                        break;
                    case "integer":
                        sb.append("private Integer "+firstLower(field.getFieldName())+";\n");
                        sb.append("@Column(unique="+unique+" ,nullable="+nullable+" )\n");
                        sb.append("public Integer get"+firstUpper(field.getFieldName())+"() {\n" +
                                "\t\treturn "+firstLower(field.getFieldName())+";\n" +
                                "}\n");
                        sb.append("public void set"+firstUpper(field.getFieldName())+"(Integer "+firstLower(field.getFieldName())+") {\n" +
                                "\t\tthis."+firstLower(field.getFieldName())+" = "+firstLower(field.getFieldName())+";\n" +
                                "\t}\n");
                        break;
                    case "text":
                        sb.append("private String "+firstLower(field.getFieldName())+";\n");
                        if(formTableInfo.getGenerationType().toLowerCase().equals("identity")){
                            sb.append("@Column(columnDefinition = \"text\" ,unique="+unique+")\n");
                        }
                        else {
                            sb.append("@Column(columnDefinition = \"LONG\" ,unique ="+unique+" )\n"); }
                        sb.append("public String get"+firstUpper(field.getFieldName())+"() {\n" +
                                "\t\treturn "+firstLower(field.getFieldName())+";\n" +
                                "\t}\n");
                        sb.append("public void set"+firstUpper(field.getFieldName())+"(String "+firstLower(field.getFieldName())+") {\n" +
                                "\t\tthis."+firstLower(field.getFieldName())+" = "+firstLower(field.getFieldName())+";\n" +
                                "\t}\n");
                        break;
                    case "image":
                        sb.append("private String "+firstLower(field.getFieldName())+";\n");
                        if(formTableInfo.getGenerationType().toLowerCase().equals("identity")){
                            sb.append("@Column(columnDefinition=\"text\" ,unique="+unique+" )\n");
                        }
                        else
                            sb.append("@Column(columnDefinition = \"LONG\" )\n");
                        sb.append("public String get"+firstUpper(field.getFieldName())+"() {\n" +
                                "\t\treturn "+firstLower(field.getFieldName())+";\n" +
                                "\t}\n");
                        sb.append("public void set"+firstUpper(field.getFieldName())+"(String "+firstLower(field.getFieldName())+") {\n" +
                                "\t\tthis."+firstLower(field.getFieldName())+" = "+firstLower(field.getFieldName())+";\n" +
                                "\t}\n");
                        break;
                    default:
                        sb.append("private String "+firstLower(field.getFieldName())+";\n");
                        sb.append("@Column(length="+field.getFieldLength()+" ,unique="+unique+" ,nullable="+nullable+" )\n");
                        sb.append("public String get"+firstUpper(field.getFieldName())+"() {\n" +
                                "\t\treturn "+firstLower(field.getFieldName())+";\n" +
                                "\t}\n");
                        sb.append("public void set"+firstUpper(field.getFieldName())+"(String "+firstLower(field.getFieldName())+") {\n" +
                                "\t\tthis."+firstLower(field.getFieldName())+" = "+firstLower(field.getFieldName())+";\n" +
                                "\t}\n");
                }

            }
            context.put("property",sb.toString());
            //输出路径
            String outpath = entityPath+"\\"+firstUpper(formTableInfo.getEntityName())+".java";
            //判断文件是否存在，如果存在就重新命名
            if(  FileUtil.exists(outpath)){
                outpath = entityPath+"\\"+firstUpper(formTableInfo.getEntityName())+ DateUtil.format(new Date(),"yyyyMMddHHmmss")+".java";
            }
            //输出
            Writer mywriter  = new PrintWriter(new FileOutputStream(  new File(outpath)));
            template.merge(context, mywriter);
            mywriter.flush();
            mywriter.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private void generateService(FormTableInfo formTableInfo,String strGeneratePath,String strPackage) throws IOException {
        //创建实体类系的文件夹
        String servicePath=strGeneratePath+"\\service\\"+firstLower(formTableInfo.getEntityPackage());
        FileUtil.makeDir(servicePath);
        //获取模板引擎
        VelocityEngine ve=getVelocityEngine(servicePath);
        try
        {
            //初始化模板
            ve.init();
            //获取模板(hello.html)
            //Velocity模板的名称
            Template template = ve.getTemplate("service.vm");
            //获取上下文
            VelocityContext context = new VelocityContext();
            //把数据填入上下文
            String   entityPackage=firstLower(formTableInfo.getEntityPackage().replace("\\",".").replace("/","."));
            context.put("package", strPackage+".service."+entityPackage);
            context.put("entityPackage", strPackage+".entity."+entityPackage+"."+firstUpper(formTableInfo.getEntityName()));
            context.put("tableName",formTableInfo.getTableName());
            context.put("entityName",firstUpper(formTableInfo.getEntityName()));
            //输出路径
            String outpath = servicePath+"\\"+firstUpper(formTableInfo.getEntityName())+"Service.java";
            //判断文件是否存在，如果存在就重新命名
            if(  FileUtil.exists(outpath)){
                outpath = servicePath+"\\"+firstUpper(formTableInfo.getEntityName())+ DateUtil.format(new Date(),"yyyyMMddHHmmss")+".java";
            }
            //输出
            Writer mywriter  = new PrintWriter(new FileOutputStream(  new File(outpath)));
            template.merge(context, mywriter);
            mywriter.flush();
            mywriter.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    private void generateController(FormTableInfo formTableInfo,String strGeneratePath,String strPackage) throws IOException {
        //创建实体类系的文件夹
        String controllerPath=strGeneratePath+"\\controller\\"+firstLower(formTableInfo.getEntityPackage());
        FileUtil.makeDir(controllerPath);
        //获取模板引擎
        VelocityEngine ve=getVelocityEngine(controllerPath);
        try
        {
            //初始化模板
            ve.init();
            //获取模板(hello.html)
            //Velocity模板的名称
            Template template = ve.getTemplate("controller.vm");
            //获取上下文
            VelocityContext context = new VelocityContext();
            //把数据填入上下文
            String   entityPackage=firstLower(formTableInfo.getEntityPackage().replace("\\",".").replace("/","."));
            context.put("package", strPackage+".controller."+entityPackage);
            context.put("entityPackage", strPackage+".entity."+entityPackage+"."+firstUpper(formTableInfo.getEntityName()));
            context.put("servicePackage", strPackage+".service."+entityPackage+"."+firstUpper(formTableInfo.getEntityName())+"Service");
            context.put("tableName",formTableInfo.getTableName());
            context.put("entityNameLower",firstLower(formTableInfo.getEntityName()));
            context.put("entityName",firstUpper(formTableInfo.getEntityName()));
            //输出路径
            String outpath = controllerPath+"\\"+firstUpper(formTableInfo.getEntityName())+"Controller.java";
            //判断文件是否存在，如果存在就重新命名
            if(  FileUtil.exists(outpath)){
                outpath = controllerPath+"\\"+firstUpper(formTableInfo.getEntityName())+ DateUtil.format(new Date(),"yyyyMMddHHmmss")+"Controller.java";
            }
            //输出
            Writer mywriter  = new PrintWriter(new FileOutputStream(  new File(outpath)));
            template.merge(context, mywriter);
            mywriter.flush();
            mywriter.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally {

        }
    }

    private void generateJS(FormTableInfo formTableInfo,String getRealPath,String generatePath,String strPackage) throws IOException {
        //创建实体类系的文件夹
        String controllerPath=getRealPath+"\\app\\"+firstLower(formTableInfo.getEntityPackage());
        FileUtil.makeDir(controllerPath);
        //获取模板引擎
        VelocityEngine ve =getVelocityEngine(generatePath);
        try
        {
            //初始化模板
            ve.init();
            //获取模板(hello.html)
            //Velocity模板的名称
            Template templateList = ve.getTemplate("pageList.vm");
            Template templateForm = ve.getTemplate("pageForm.vm");
            //获取上下文
            VelocityContext contextList = new VelocityContext();
            VelocityContext contextForm = new VelocityContext();
            //把数据填入上下文
            contextList.put("entityNameLower",firstLower(formTableInfo.getEntityName()));
            contextForm.put("entityNameLower",firstLower(formTableInfo.getEntityName()));

            List<FormTableField>   listField= formTableFieldService.getTableField(formTableInfo.getTableId());
            StringBuilder sbFields=new StringBuilder();
             String tempField=null;
            StringBuilder sbSearchFlds=new StringBuilder();
            StringBuilder sbSearchFldsGet=new StringBuilder();
            sbFields.append("{xtype:'hidden',\n" +
                    "\t\t\t\t\tname : 'id',\n" +
                    "\t\t\t\t\tdataIndex : 'id'\n" +
                    "\t\t\t\t},\n");

            sbFields.append("{xtype:'hidden',\n" +
                    "\t\t\t\t\tname : 'deleteFlag',\n" +
                    "\t\t\t\t\tdataIndex : 'deleteFlag'\n" +
                    "\t\t\t\t},\n");

            int tempColSpan = 0;
            for(FormTableField field:listField){
                tempField=new String();
                //allowBlank 可选,是否设置该列的值可以为空(默认值false)
                boolean allowBlank=!field.getMustFill().equals(1);
                switch(field.getControlType()){
                    case"datefield":
                        tempField=     " new dateTime({\n" +
                                "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                "                    format:'Y-m-d H:i:s',\n" +
                                "                    fieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                "                    allowBlank : "+allowBlank+"\n" +
                                "                }),\n";
                        //查询
                        if(field.getDispQuery().equals(1)){
                            sbSearchFlds.append("searchFlds.add(begin'"+firstLower(field.getFieldName())+"', new dateTime({\n" +
                                    "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    format:'Y-m-d H:i:s',\n" +
                                    "                    fieldLabel : '"+field.getFieldDisplayName()+"'\n" +
                                    "                }));\n");
                            sbSearchFldsGet.append("searchFlds.get('begin"+firstLower(field.getFieldName())+"'),");
                            sbSearchFlds.append("searchFlds.add(end'"+firstLower(field.getFieldName())+"', new dateTime({\n" +
                                    "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    format:'Y-m-d H:i:s',\n" +
                                    "                }));\n");
                            sbSearchFldsGet.append("searchFlds.get('end"+firstLower(field.getFieldName())+"'),\n");
                        }
                        break;
                    case"numberfield":
                        //是能数据整形
                        boolean allowDecimals=   !field.getFieldType().equals("Integer") ;
                        if(field.getCodeName().isEmpty()){
                            tempField=   "{xtype:'numberfield',\n" +
                                    "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                    "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    allowDecimals : "+allowDecimals+",\n" +
                                    "                    decimalPrecision : "+field.getDecimalPlaces()+",\n" +
                                    "                    fieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                    "                    allowBlank : "+allowBlank+"\n" +
                                    "\t\t\t\t}\n";
                        }
                        else{
                            tempField= " new comboBox({\n" +
                                    "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    fieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                    "                    labelAlign : 'right',\n" +
                                    "                    codeName:'"+field.getCodeName()+"',\n" +
                                    "                    queryMode: 'local',\n" +
                                    "                    typeAhead : false,\n" +
                                    "                    forceSelection : true,\n" +
                                    "                    loadingText : '正在搜索...',\n" +
                                    "                    allowBlank : "+allowBlank+",\n" +
                                    "                    hideTrigger : false\n" +
                                    "                })\n";
                        }
                        //查询
                        if(field.getDispQuery().equals(1)){
                            if(field.getCodeName().isEmpty()){
                                sbSearchFlds.append("searchFlds.add('"+firstLower(field.getFieldName())+"', new Ext.form.NumberField({\n" +
                                    "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    allowDecimals : "+allowDecimals+",\n" +
                                    "                    decimalPrecision : "+field.getDecimalPlaces()+",\n" +
                                    "                    fieldLabel : '"+field.getFieldDisplayName()+"'\n" +
                                    "                }));\n");
                        }
                        else{
                                sbSearchFlds.append("searchFlds.add('"+firstLower(field.getFieldName())+"',new comboBox({\n" +
                                    "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    fieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                    "                    labelAlign : 'right',\n" +
                                    "                    codeName:'"+field.getCodeName()+"',\n" +
                                    "                    queryMode: 'local',\n" +
                                    "                    typeAhead : false,\n" +
                                    "                    forceSelection : true,\n" +
                                    "                    loadingText : '正在搜索...',\n" +
                                    "                    hideTrigger : false\n" +
                                    "                }));\n");
                        }
                            sbSearchFldsGet.append("searchFlds.get('end"+firstLower(field.getFieldName())+"'),\n");
                        }
                            break;
                    case"textarea":

                        tempField=   "{xtype:'textarea',\n" +
                                "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tfieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                "\t\t\t\t\tallowBlank : "+allowBlank+"\n"  +
                                "\t\t\t\t}\n";
                                  break;
                    case"textfield":
                                if(field.getCodeName().isEmpty()){
                                    tempField=   "{xtype:'textfield',\n" +
                                            "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                            "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                            "\t\t\t\t\tfieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                            "\t\t\t\t\tallowBlank : "+allowBlank+"\n"  +
                                            "\t\t\t\t}\n";

                                }
                        else{

                                    tempField= " new comboBox({\n" +
                                            "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                            "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                            "                    fieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                            "                    labelAlign : 'right',\n" +
                                            "                    codeName:'"+field.getCodeName()+"',\n" +
                                            "                    queryMode: 'local',\n" +
                                            "                    typeAhead : false,\n" +
                                            "                    forceSelection : true,\n" +
                                            "                    loadingText : '正在搜索...',\n" +
                                            "\t\t\t\t\tallowBlank : "+allowBlank+",\n"  +
                                            "                    hideTrigger : false\n" +
                                            "                })\n";
                                }
                        //查询
                        if(field.getDispQuery().equals(1)){
                            if(field.getCodeName().isEmpty()){
                                sbSearchFlds.append("searchFlds.add('"+firstLower(field.getFieldName())+"', new Ext.form.TextField({\n" +
                                        "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                        "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                        "\t\t\t\t\tfieldLabel : '"+field.getFieldDisplayName()+"'\n" +
                                        "\t\t\t\t}));\n");
                            }
                            else{
                                sbSearchFlds.append("searchFlds.add('"+firstLower(field.getFieldName())+"',new comboBox({\n" +
                                        "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                        "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                        "                    fieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                        "                    labelAlign : 'right',\n" +
                                        "                    codeName:'"+codeService.getName(Long.valueOf(field.getCodeName()))+"',\n" +
                                        "                    queryMode: 'local',\n" +
                                        "                    typeAhead : false,\n" +
                                        "                    forceSelection : true,\n" +
                                        "                    loadingText : '正在搜索...',\n" +
                                        "                    hideTrigger : false\n" +
                                        "                }));\n");
                            }
                            sbSearchFldsGet.append("searchFlds.get('end"+firstLower(field.getFieldName())+"'),\n");
                        }
                        break;
                    case"hidden":
                        tempField=   "{xtype:'hidden',\n" +
                                "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tfieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                "\t\t\t\t\tallowBlank : "+allowBlank+"\n"  +
                                "\t\t\t\t}\n";
                        break;
                    case "file":
                        tempField=   "{xtype:'filefield',\n" +
                                "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tfieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                "\t\t\t\t\tallowBlank : "+allowBlank+"\n"  +
                                "\t\t\t\t}\n";
                        break;
                    default:
                        tempField=   "{xtype:'textfield',\n" +
                                "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tfieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                "\t\t\t\t\tallowBlank : "+allowBlank+"\n"  +
                                "\t\t\t\t}\n";
                        break;
                }

                     //控件位置
                    if(field.getColspan().equals(0) ){
                        if(tempColSpan%2==1){
                            sbFields.append(tempField+"]},");
                            tempColSpan=0;
                        }
                        else{
                        sbFields.append("{\n" +
                                "                            xtype: 'container',\n" +
                                "                            layout: 'hbox',\n" +
                                "                            margin: '0 0 5 0',\n" +
                                "                            defaults: {\n" +
                                "                        flex: 1\n" +
                                "                    }, items: [ "+tempField+"," );
                            tempColSpan++;
                        }
                    }
                    else{
                        if(tempColSpan%2==1) {
                            sbFields.append(tempField+"]},\n");
                            tempColSpan=0;
                        }
                        else
                            sbFields.append(tempField+",\n");
                    }


            }
            if(tempColSpan%2==1){
                sbFields.append("null]},");
            }


            if(!sbFields.toString().isEmpty())
            contextForm.put("fields",sbFields.toString().subSequence(0,sbFields.toString().length()-1));
            else
                contextForm.put("fields","");
            contextForm.put("package",firstLower(formTableInfo.getEntityPackage().replace("\\",".").replace("/",".")));

            contextList.put("searchFlds",sbSearchFlds.toString());
            if(!sbSearchFldsGet.toString().isEmpty())
                contextList.put("searchFldsGet",sbSearchFldsGet.toString().subSequence(0,sbSearchFldsGet.toString().length()-1));
             else
                contextList.put("searchFldsGet","");
            contextList.put("entityPackage", strPackage+".entity."+firstLower(formTableInfo.getEntityPackage().replace("\\",".").replace("/","."))+"."+firstUpper(formTableInfo.getEntityName()));
            contextList.put("package",firstLower(formTableInfo.getEntityPackage().replace("\\",".").replace("/",".")));
            //输出路径
            String outpath = controllerPath+"\\"+firstLower(formTableInfo.getEntityName())+"List.js";
            //判断文件是否存在，如果存在就重新命名
            if(  FileUtil.exists(outpath)){
                outpath = controllerPath+"\\"+firstLower(formTableInfo.getEntityName())+ DateUtil.format(new Date(),"yyyyMMddHHmmss")+".js";
            }
            //输出 List
            Writer mywriter  = new PrintWriter(new FileOutputStream(  new File(outpath)));
            templateList.merge(contextList, mywriter);
            mywriter.flush();
            mywriter.close();
            outpath = controllerPath+"\\"+firstLower(formTableInfo.getEntityName())+"Form.js";
             //Form
            //判断文件是否存在，如果存在就重新命名
            if(  FileUtil.exists(outpath)){
                outpath = controllerPath+"\\"+firstLower(formTableInfo.getEntityName())+ DateUtil.format(new Date(),"yyyyMMddHHmmss")+".js";
            }
            mywriter  = new PrintWriter(new FileOutputStream(  new File(outpath)));
            templateForm.merge(contextForm, mywriter);
            mywriter.flush();
            mywriter.close();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally {

        }
    }
    private void generatePage(FormTableInfo formTableInfo,String getRealPath,String generatePath,String strPackage) throws IOException {
        //创建实体类系的文件夹
        String controllerPath=getRealPath+"\\"+firstLower(formTableInfo.getEntityPackage());
        FileUtil.makeDir(controllerPath);
        //获取模板引擎
        VelocityEngine ve =getVelocityEngine(generatePath);

        try
        {
            //初始化模板
            ve.init();
            //获取模板(hello.html)
            //Velocity模板的名称
            Template template = ve.getTemplate("page.vm");
            //获取上下文
            VelocityContext context = new VelocityContext();
            //把数据填入上下文
            context.put("tableName",formTableInfo.getTableName());
            context.put("entityNameLower",firstLower(formTableInfo.getEntityName()));
            List<FormTableField>   listField= formTableFieldService.getTableField(formTableInfo.getTableId());
            StringBuilder sbFields=new StringBuilder();
            StringBuilder sbFieldsGet=new StringBuilder();
            StringBuilder sbSearchFlds=new StringBuilder();
            StringBuilder sbSearchFldsGet=new StringBuilder();
            sbFields.append("this.fields.add('id', new Ext.form.Hidden({\n" +
                    "\t\t\t\t\tname : 'id',\n" +
                    "\t\t\t\t\tdataIndex : 'id'\n" +
                    "\t\t\t\t}));\n");
            sbFieldsGet.append("this.fields.get('id'),");
            sbFields.append("this.fields.add('deleteFlag', new Ext.form.Hidden({\n" +
                    "\t\t\t\t\tname : 'deleteFlag',\n" +
                    "\t\t\t\t\tdataIndex : 'deleteFlag'\n" +
                    "\t\t\t\t}));\n");
            sbFieldsGet.append("this.fields.get('deleteFlag'),");
            int tempColSpan = 0;
            for(FormTableField field:listField){
                //allowBlank 可选,是否设置该列的值可以为空(默认值false)
                boolean allowBlank=!field.getMustFill().equals(1);
                switch(field.getControlType()){
                    case"datefield":

                        sbFields.append("this.fields.add('"+firstLower(field.getFieldName())+"', new dateTime({\n" +
                                "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                "                    format:'Y-m-d H:i:s',\n" +
                                "                    fieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                "                    allowBlank : "+allowBlank+"\n" +
                                "                }));\n");
                        //查询
                        if(field.getDispQuery().equals(1)){
                            sbSearchFlds.append("searchFlds.add(begin'"+firstLower(field.getFieldName())+"', new dateTime({\n" +
                                    "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    format:'Y-m-d H:i:s',\n" +
                                    "                    fieldLabel : '"+field.getFieldDisplayName()+"'\n" +
                                    "                }));\n");
                            sbSearchFldsGet.append("searchFlds.get('begin"+firstLower(field.getFieldName())+"'),");
                            sbSearchFlds.append("searchFlds.add(end'"+firstLower(field.getFieldName())+"', new dateTime({\n" +
                                    "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    format:'Y-m-d H:i:s',\n" +
                                    "                }));\n");
                            sbSearchFldsGet.append("searchFlds.get('end"+firstLower(field.getFieldName())+"'),\n");
                        }
                        break;
                    case"numberfield":
                        //是能数据整形
                        boolean allowDecimals=   !field.getFieldType().equals("Integer") ;
                        if(field.getCodeName().isEmpty()){
                            sbFields.append("this.fields.add('"+firstLower(field.getFieldName())+"', new Ext.form.NumberField({\n" +
                                    "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    allowDecimals : "+allowDecimals+",\n" +
                                    "                    decimalPrecision : "+field.getDecimalPlaces()+",\n" +
                                    "                    fieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                    "                    allowBlank : "+allowBlank+"\n" +
                                    "                }));\n");
                        }
                        else{
                            sbFields.append("this.fields.add('"+firstLower(field.getFieldName())+"',new comboBox({\n" +
                                    "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    fieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                    "                    labelAlign : 'right',\n" +
                                    "                    codeName:'"+field.getCodeName()+"',\n" +
                                    "                    queryMode: 'local',\n" +
                                    "                    typeAhead : false,\n" +
                                    "                    forceSelection : true,\n" +
                                    "                    loadingText : '正在搜索...',\n" +
                                    "                    allowBlank : "+allowBlank+",\n" +
                                    "                    hideTrigger : false\n" +
                                    "                }));\n");
                        }
                        //查询
                        if(field.getDispQuery().equals(1)){
                            if(field.getCodeName().isEmpty()){
                                sbSearchFlds.append("searchFlds.add('"+firstLower(field.getFieldName())+"', new Ext.form.NumberField({\n" +
                                        "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                        "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                        "                    allowDecimals : "+allowDecimals+",\n" +
                                        "                    decimalPrecision : "+field.getDecimalPlaces()+",\n" +
                                        "                    fieldLabel : '"+field.getFieldDisplayName()+"'\n" +
                                        "                }));\n");
                            }
                            else{
                                sbSearchFlds.append("searchFlds.add('"+firstLower(field.getFieldName())+"',new comboBox({\n" +
                                        "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                        "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                        "                    fieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                        "                    labelAlign : 'right',\n" +
                                        "                    codeName:'"+field.getCodeName()+"',\n" +
                                        "                    queryMode: 'local',\n" +
                                        "                    typeAhead : false,\n" +
                                        "                    forceSelection : true,\n" +
                                        "                    loadingText : '正在搜索...',\n" +
                                        "                    hideTrigger : false\n" +
                                        "                }));\n");
                            }
                            sbSearchFldsGet.append("searchFlds.get('end"+firstLower(field.getFieldName())+"'),\n");
                        }
                        break;
                    case"textarea":
                        sbFields.append("this.fields.add('"+firstLower(field.getFieldName())+"', new Ext.form.TextArea({\n" +
                                "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tfieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                "\t\t\t\t\tallowBlank : "+allowBlank+"\n"  +
                                "\t\t\t\t}));\n");

                        break;
                    case"textfield":
                        if(field.getCodeName().isEmpty()){
                            sbFields.append("this.fields.add('"+firstLower(field.getFieldName())+"', new Ext.form.TextField({\n" +
                                    "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                    "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                    "\t\t\t\t\tfieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                    "\t\t\t\t\tallowBlank : "+allowBlank+"\n"  +
                                    "\t\t\t\t}));\n");
                        }
                        else{
                            sbFields.append("this.fields.add('"+firstLower(field.getFieldName())+"',new comboBox({\n" +
                                    "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                    "                    fieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                    "                    labelAlign : 'right',\n" +
                                    "                    codeName:'"+field.getCodeName()+"',\n" +
                                    "                    queryMode: 'local',\n" +
                                    "                    typeAhead : false,\n" +
                                    "                    forceSelection : true,\n" +
                                    "                    loadingText : '正在搜索...',\n" +
                                    "\t\t\t\t\tallowBlank : "+allowBlank+",\n"  +
                                    "                    hideTrigger : false\n" +
                                    "                }));\n");
                        }
                        //查询
                        if(field.getDispQuery().equals(1)){
                            if(field.getCodeName().isEmpty()){
                                sbSearchFlds.append("searchFlds.add('"+firstLower(field.getFieldName())+"', new Ext.form.TextField({\n" +
                                        "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                        "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                        "\t\t\t\t\tfieldLabel : '"+field.getFieldDisplayName()+"'\n" +
                                        "\t\t\t\t}));\n");
                            }
                            else{
                                sbSearchFlds.append("searchFlds.add('"+firstLower(field.getFieldName())+"',new comboBox({\n" +
                                        "                    name : '"+firstLower(field.getFieldName())+"',\n" +
                                        "                    dataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                        "                    fieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                        "                    labelAlign : 'right',\n" +
                                        "                    codeName:'"+codeService.getName(Long.valueOf(field.getCodeName()))+"',\n" +
                                        "                    queryMode: 'local',\n" +
                                        "                    typeAhead : false,\n" +
                                        "                    forceSelection : true,\n" +
                                        "                    loadingText : '正在搜索...',\n" +
                                        "                    hideTrigger : false\n" +
                                        "                }));\n");
                            }
                            sbSearchFldsGet.append("searchFlds.get('end"+firstLower(field.getFieldName())+"'),\n");
                        }
                        break;
                    case"hidden":
                        sbFields.append("this.fields.add('"+firstLower(field.getFieldName())+"', new Ext.form.Hidden({\n" +
                                "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"'\n" +
                                "\t\t\t\t}));\n");
                        break;
                    case "file":
                        sbFields.append("this.fields.add('"+firstLower(field.getFieldName())+"', {\n" +
                                " xtype: 'filefield',"+
                                "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tfieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                "\t\t\t\t\tallowBlank : "+allowBlank+"\n" +
                                "\t\t\t\t});\n");
                        break;
                    default:
                        sbFields.append("this.fields.add('"+firstLower(field.getFieldName())+"', new Ext.form.TextField({\n" +
                                "\t\t\t\t\tname : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tdataIndex : '"+firstLower(field.getFieldName())+"',\n" +
                                "\t\t\t\t\tfieldLabel : '"+field.getFieldDisplayName()+"',\n" +
                                "\t\t\t\t\tallowBlank : "+allowBlank+"\n"  +
                                "\t\t\t\t}));\n");
                        break;
                }

                //控件位置
                if(field.getColspan().equals(0) ){
                    if(tempColSpan%2==1){
                        sbFieldsGet.append("this.fields.get('"+firstLower(field.getFieldName())+"')]},");
                        tempColSpan=0;
                    }
                    else{
                        sbFieldsGet.append("{\n" +
                                "                            xtype: 'container',\n" +
                                "                            layout: 'hbox',\n" +
                                "                            margin: '0 0 5 0',\n" +
                                "                            defaults: {\n" +
                                "                        flex: 1,\n" +
                                "                        hideLabel: true\n" +
                                "                    }, items: [ this.fields.get('"+firstLower(field.getFieldName())+"')," );
                        tempColSpan++;
                    }
                }
                else{
                    if(tempColSpan%2==1) {
                        sbFieldsGet.append("this.fields.get('"+firstLower(field.getFieldName())+"')]},\n");
                        tempColSpan=0;
                    }
                    else
                        sbFieldsGet.append("this.fields.get('"+firstLower(field.getFieldName())+"'),\n");
                }


            }
            if(tempColSpan%2==1){
                sbFieldsGet.append("null]},");
            }

            context.put("fields",sbFields.toString());
            if(!sbFieldsGet.toString().isEmpty())
                context.put("fieldsGet",sbFieldsGet.toString().subSequence(0,sbFieldsGet.toString().length()-1));
            else
                context.put("fieldsGet","");
            context.put("searchFlds",sbSearchFlds.toString());
            if(!sbSearchFldsGet.toString().isEmpty())
                context.put("searchFldsGet",sbSearchFldsGet.toString().subSequence(0,sbSearchFldsGet.toString().length()-1));
            else
                context.put("searchFldsGet","");
            context.put("entityPackage", strPackage+".entity."+firstLower(formTableInfo.getEntityPackage().replace("\\",".").replace("/","."))+"."+firstUpper(formTableInfo.getEntityName()));

            //输出路径
            String outpath = controllerPath+"\\"+firstLower(formTableInfo.getEntityName())+".jsp";
            //判断文件是否存在，如果存在就重新命名
            if(  FileUtil.exists(outpath)){
                outpath = controllerPath+"\\"+firstLower(formTableInfo.getEntityName())+ DateUtil.format(new Date(),"yyyyMMddHHmmss")+".jsp";
            }
            //输出
            Writer mywriter  = new PrintWriter(new FileOutputStream(  new File(outpath)));
            template.merge(context, mywriter);
            mywriter.flush();
            mywriter.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally {

        }
    }

}
